package structure.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * 享元工厂
 */
public class CityFlyWeightFactory {
    // 享元模式，使用Map来存储享元对象，key是内蕴状态，value是享元对象 static 静态保证是单例
    private static  Map<String, CityFlyWeight> files = new HashMap<String, CityFlyWeight>();

    /**
     * 获取享元对象
     * @param state
     * @return
     */
    public static CityFlyWeight getFlyWeight(String  state) {
        System.out.println("享元工厂对象：" + files);
        // 先从缓存中查找
        if (files.containsKey(state)) {
            System.out.println("缓存中存在，直接从缓存中获取" + state);
            return files.get(state);
        } else {
            if (state.startsWith("street")){
                CityFlyWeight flyWeight = new StreetFlyWeight(state);
                files.put(state, flyWeight);
                return flyWeight;
            }
            if(state.startsWith("house")) {
                CityFlyWeight flyWeight = new HouseFlyWeight(state);
                files.put(state, flyWeight);
                return flyWeight;
            }
            // person 对象是不支持共享的 每次都需要新创建一个对象
            if(state.startsWith("person")) {
                CityFlyWeight flyWeight = new PersonUnsharedFlyWeight(state);
                return flyWeight;
            }

        return null;

        }
    }
}
